/*

Input: tmp/panel_wahlen_covted_ltw18.dta [address panel converted to 2018 delineations]

Output: tmp/voter_panel_pp_dist.dta
			[address panel with distances between polling locations (wl_street_dist)]

Main task: Calculate distances BETWEEN old and new polling locations


Note: 
	> To calculate walking distances, module 'osrmtime' is required; to install follow
		the following steps (only for windows):	

		1. osrmtime package downloaded from github (https://github.com/christophrust/osrmtime),
			saved & unzipped in folder: 05_package
		2. Downloaded OSRM basemap for 'Oberbayern' from http://download.geofabrik.de/europe/germany/bayern.html
			and saved in folder: 05_package/osrm_basemaps
		3. to install, execute:
			cd "$project/05_packages/osrmtime_release1.3.3/"
			net describe osrmtime.pkg, from("$project/05_packages/osrmtime_release1.3.3/")
			net install osrmtime.pkg
			net get osrmtime.pkg
			shell osrminstall.cmd
			cd "$project"
		5. prepare basemaps, execute:
			osrmprepare, mapfile("$project/05_packages/osrm_basemaps/oberbayern-latest.osm.pbf") profile(foot) ///
			osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14") 


*/


** PULL: voter-address panel
use "$tmp/panel_wahlen_covted_ltw18.dta", clear

	// keep relevant vars
	keep voter_id wahl_id wl_id lat_wl lon_wl

	// gen lags for Polling place
	gen double l_lat_wl = .
	gen double l_lon_wl = .
	gen l_wl_id = ""

	sort voter_id wahl_id
	bys voter_id (wahl_id): replace l_wl_id = wl_id[_n-1]
	bys voter_id (wahl_id): replace l_lon_wl = lon_wl[_n-1]
	bys voter_id (wahl_id): replace l_lat_wl = lat_wl[_n-1]
	
	// drop FE-09
	drop if wahl_id==0 

	// ID for unique pair of current and past PP (to calc distances)
	egen pair_id = group(l_wl_id wl_id)
	
	// TEMPSAVE
	tempfile panel_wl_lag
	save `panel_wl_lag'

	// KEEP only unique pairs
	drop voter_id wahl_id
	gduplicates drop pair_id, force


 * Calculate walking distance between PP in t and t-1
	cd "$project/05_packages/osrmtime_release1.3.3/"
	 osrmtime lat_wl lon_wl l_lat_wl l_lon_wl, mapfile("$project/05_packages/osrm_basemap/oberbayern-latest.osrm") ///
		osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14")
	cd "$project"	
	
	rename 	distance wl_street_dist
	assert wl_street_dist==0 if wl_id==l_wl_id
	replace wl_street_dist=wl_street_dist/1000 // rescale km
	lab var wl_street_dist "street distance b/w polling place in t and t-1 in km"
	

	// merge back to full panel
	keep pair_id wl_street_dist
	merge 1:m pair_id using `panel_wl_lag', assert(3) nogen
		
	// drop lags 
	drop l_*

 * save: 
	compress
	isid voter_id wahl_id 
	save "$tmp/voter_panel_pp_dist.dta", replace
